package com.workcell.workdata.im.model.misc;

import org.apache.commons.io.IOUtils;
import org.apache.tomcat.util.codec.binary.Base64;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;

public class Base64MultipartFile implements MultipartFile {

    private final byte[] content;
    private final String header;

    public Base64MultipartFile(byte[] content, String header) {
        this.content = content;
        this.header = header.split(";")[0];
    }

    @Override
    public String getName() {
        return System.currentTimeMillis() + Math.random() + "." + header.split("/")[1];
    }

    @Override
    public String getOriginalFilename() {
        return getName();
    }

    @Override
    public String getContentType() {
        return header.split(":")[1];
    }

    @Override
    public boolean isEmpty() {
        return content == null || content.length == 0;
    }

    @Override
    public long getSize() {
        return content.length;
    }

    @Override
    public byte[] getBytes() {
        return content;
    }

    @Override
    public InputStream getInputStream() {
        return new ByteArrayInputStream(content);
    }

    @Override
    public void transferTo(File file) throws IOException, IllegalStateException {
        IOUtils.write(content,new FileOutputStream(file));
    }

    public static MultipartFile of(String base64) throws IOException {
        String[] array = base64.split(",");

        String header = array[0];
        String content = array[1];
        byte[] bytes =  Base64.decodeBase64(content);
        for(int i = 0; i < bytes.length; ++i) {
            if (bytes[i] < 0) {
                bytes[i] += 256;
            }
        }
        return new Base64MultipartFile(bytes,header);
    }
}
